﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.Commerce.Contexts.Categories;
using Kooboo.Commerce;
using Kooboo.Commerce.Contexts.Brands;
using Kooboo.Commerce.Services;


namespace Kooboo.Web.UI
{
    public static class TreeViewer
    {
        #region Category

        public static MvcHtmlString TreeViewerFor(this HtmlHelper htmlHelper, ICategory active)
        {
            StringBuilder html = new StringBuilder();

            var host = new ServiceHost();

            var categories = host.QueryCategories().OrderBy(i => i.Name).ToList();
          

            var actviedList = new List<ICategory>();

            if (active != null)
            {
                var selected = categories.Where(i => i.Id == active.Id).FirstOrDefault();

                if (selected != null)
                {
                    actviedList.Add(selected);
                    while (selected.Parent != null)
                    {
                        actviedList.Add(selected.Parent);
                        selected = selected.Parent;
                    }
                }
            }

            html.AppendLine("<ul>");

            foreach (var i in categories.Where(i => i.Parent == null))
            {
                html.Append(BuildHtmlItem(i, actviedList));
            }

            html.AppendLine("</ul>");

            return MvcHtmlString.Create(html.ToString());
        }

        static string BuildHtmlItem(ICategory category, List<ICategory> actviedList)
        {
            var html = "";

            if (actviedList.Contains(category))
            {
                html += "<li class=active><a href=/categories/" + category.Id + ">" + System.Web.HttpUtility.HtmlEncode(category.Name) + "</a>";
                if (category.Children.Count() > 0)
                {
                    html += "<ul>";
                    foreach (var i in category.Children.OrderBy(i => i.Name))
                    {
                        html += BuildHtmlItem(i, actviedList);
                    }

                    html += "</ul>";
                }
            }
            else
            {
                html += "<li><a href=/categories/" + category.Id + ">" + System.Web.HttpUtility.HtmlEncode(category.Name) + "</a>";
            }

            

            html += "</li>";
            return html;
        }

        #endregion
    }
}